package entity.file;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.File;
import java.io.FileWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ：mmzs
 * @date ：Created in 2020/9/13 17:45
 * @description：从XML文件读文章信息
 * @modified By：
 * @version: $
 */
public class PdfFile extends AbstractFile {

    public PdfFile(int id, File file) {
        this.id = id;
        this.file = file;
        this.path = file.getPath();
    }

    @Override
    public String loadTextFromFile() {
        File inputFile = this.file;
        //创建文档对象
        PDDocument doc = null;
        String content = "";
        try {
            //加载一个pdf对象
            doc = PDDocument.load(inputFile);
            //获取一个PDFTextStripper文本剥离对象
            PDFTextStripper textStripper = new PDFTextStripper();
            content = textStripper.getText(doc);
            File txtFile = new File(inputFile.getPath().replace("pdf", "txt"));
            FileWriter fileWriter = new FileWriter(txtFile);
            fileWriter.write(content);
            fileWriter.close();
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    public boolean isFooterLine(String input) {
        String[] arr = new String[]{
                "http://", "https://", "All rights reserved", "Corresponding author",
                "doi:", "URL:", "Tel.", "PII", "pii", "Email:", "SSDI", "E-mail", "phone"
        };
        for (String s : arr) {
            if (input.contains(s)) {
                return true;
            }
        }
        return false;
    }

    public String removeHeaderAndFooterOnNewVersionPdf(String input) {
        String headerPattern = "/ Artificial Intelligence \\d+ \\(\\d+\\) \\d+\\–\\d+";
        Matcher m = Pattern.compile(headerPattern).matcher(input);
        if (m.find()) {
            int start = m.start();
            int end = m.end();
            String twoChar = null;
            do {
                start--;
                twoChar = input.substring(start - 1, start);
            } while (!twoChar.equals("\n"));
            String header = input.substring(start, end);

//            这里是第一次出现页眉的位置,开始往上找页脚
            int footerEnd = start;
            int footerLineStart = start;
            int footerLineEnd = -1;
            String footerLine = null;
            do {
                footerLineEnd = footerLineStart;
                footerLineStart = readLineReverse(input, footerLineEnd);
                footerLine = input.substring(footerLineStart, footerLineEnd);
            } while (isFooterLine(footerLine));
//            页脚找到了，去掉页脚
            String footerText = input.substring(footerLineEnd, footerEnd);
            input = input.replace(footerText, "");

//            开始找页眉
            String[] headerSplit = header.split(" ");
            String[] pages = headerSplit[headerSplit.length - 1].split("–");
            int startPage = Integer.parseInt(pages[0]);
            int endPage = Integer.parseInt(pages[1]);
            if (startPage % 2 == 1 && header.startsWith(Integer.toString(startPage + 1))) {
                header = header.substring(pages[0].length() + 1);
            }
//            奇数在右，偶数在左
            for (int i = startPage + 1; i <= endPage; i++) {
                String textToBeReplaced = null;
                if (i % 2 == 1) {
                    textToBeReplaced = header + " " + i;
                } else {
                    textToBeReplaced = "" + i + " " + header;
                }
                if (input.contains(textToBeReplaced)) {
//                    有些没有页眉
                    input = input.replace(textToBeReplaced, "");
//                    页眉被去掉了
                }
            }
        } else {
            return "fail";
        }
        return input;
    }

    public String removeHeaderAndFooterOnOldVersionPdf(String input) {
        String headerPattern = "/Ar\\S+ I";
        StringBuilder result = new StringBuilder(input);
        Matcher m = Pattern.compile(headerPattern).matcher(result);
        int i = 0;
        while (m.find()) {
            int[] ints = readLineCurrent(result, m.start());
            if (i == 0) {
                i = 1;
//                这里是第一次出现页眉的位置,开始往上找页脚
                int footerEnd = ints[0];
                int footerLineStart = ints[0];
                int footerLineEnd = -1;
                String footerLine = null;
                do {
                    footerLineEnd = footerLineStart;
                    footerLineStart = readLineReverse(result, footerLineEnd);
                    footerLine = result.substring(footerLineStart, footerLineEnd);
                } while (isFooterLine(footerLine));
//            页脚找到了，去掉页脚
                result.replace(footerLineEnd, footerEnd, "");
            } else {
                result.replace(ints[0], ints[1], "");
            }
            m.reset();
        }
        return result.toString();
    }

    public String removeHeaderAndFooter(String input) throws Exception {
        String s = removeHeaderAndFooterOnNewVersionPdf(input);
        if ("fail".equals(s)) {
            s = removeHeaderAndFooterOnOldVersionPdf(input);
        }
        return s;
    }

    public static void main(String[] args) {
        new PdfFile(1234, new File("G:\\pdfpaper\\ai\\0004370294000202.pdf"));
    }
}
